package cn.edu.ctbu.dp01.controller;

import cn.edu.ctbu.dp01.common.Result;
import cn.edu.ctbu.dp01.entity.Student;
import cn.edu.ctbu.dp01.exception.BusinessException;
import cn.edu.ctbu.dp01.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/students")
public class StudentRestController {

    @Autowired
    private StudentService studentService;

    // 分页查询学生列表（支持多属性查询）
    @GetMapping
    public Result<Map<String, Object>> getStudents(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String sno,
            @RequestParam(required = false) Integer age,
            @RequestParam(required = false) Integer sex) {
        
        Pageable pageable = PageRequest.of(page - 1, limit);
        Page<Student> studentPage = studentService.findStudentsWithFilters(name, sno, age, sex, pageable);
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", studentPage.getContent());
        result.put("count", studentPage.getTotalElements());
        result.put("msg", "查询成功");
        result.put("code", 0);
        
        return Result.success(result);
    }

    // 根据ID获取学生
    @GetMapping("/{id}")
    public Result<Student> getStudentById(@PathVariable Integer id) {
        Student student = studentService.findById(id);
        if (student == null) {
            throw new BusinessException("未找到ID为" + id + "的学生");
        }
        return Result.success(student);
    }

    // 添加学生
    @PostMapping
    public Result<Student> addStudent(@RequestBody Student student) {
        // 参数校验
        validateStudent(student);
        
        Student savedStudent = studentService.save(student);
        return Result.success(savedStudent);
    }

    // 更新学生
    @PutMapping("/{id}")
    public Result<Student> updateStudent(@PathVariable Integer id, @RequestBody Student student) {
        // 验证学生是否存在
        Student existingStudent = studentService.findById(id);
        if (existingStudent == null) {
            throw new BusinessException("未找到ID为" + id + "的学生");
        }
        
        // 参数校验
        validateStudent(student);
        
        student.setId(id);
        Student updatedStudent = studentService.save(student);
        return Result.success(updatedStudent);
    }

    // 删除学生
    @DeleteMapping("/{id}")
    public Result<Object> deleteStudent(@PathVariable Integer id) {
        // 验证学生是否存在
        Student existingStudent = studentService.findById(id);
        if (existingStudent == null) {
            throw new BusinessException("未找到ID为" + id + "的学生");
        }
        
        studentService.deleteById(id);
        return Result.success("删除成功");
    }

    // 批量删除学生
    @DeleteMapping
    public Result<Object> deleteStudents(@RequestBody Integer[] ids) {
        for (Integer id : ids) {
            Student existingStudent = studentService.findById(id);
            if (existingStudent != null) {
                studentService.deleteById(id);
            }
        }
        return Result.success("批量删除成功");
    }

    private void validateStudent(Student student) {
        if (student.getName() == null || student.getName().trim().isEmpty()) {
            throw new BusinessException("学生姓名不能为空");
        }
        if (student.getSno() == null || student.getSno().trim().isEmpty()) {
            throw new BusinessException("学号不能为空");
        }
        if (student.getAge() == null || student.getAge() < 0) {
            throw new BusinessException("年龄不能为空且必须为正数");
        }
        if (student.getSex() == null || (student.getSex() != 0 && student.getSex() != 1)) {
            throw new BusinessException("性别必须为男(1)或女(0)");
        }
    }
}